package com.mk.admin.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.mk.admin.mapper.DoctorMapper;
import com.mk.admin.mapper.PayOrderMapper;
import com.mk.admin.model.ResultDto;
import com.mk.admin.model.dto.*;
import com.mk.admin.model.entity.DoctorEntity;
import com.mk.admin.model.entity.PayOrderEntity;
import com.mk.admin.model.query.*;
import com.mk.admin.model.vo.DoctorAreaTimeVo;
import com.mk.admin.model.vo.DoctorSchedulingVo;
import com.mk.admin.model.vo.DoctorVo;
import com.mk.admin.service.DoctorService;
import com.mk.admin.service.PayOrderService;
import com.mk.admin.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class DoctorServiceImpl implements DoctorService {
    @Autowired
    private DoctorMapper doctorMapper;
    @Autowired
    private PayOrderMapper payOrderMapper;

    @Override
    public ResultDto select(DoctorQuery query) {

        return ResultDto.builder()
                .result(doctorMapper.select(JSONCopy.copy(query, DoctorEntity.class)))
                .count(doctorMapper.count(JSONCopy.copy(query, DoctorEntity.class)))
                .retCode("T")
                .build();
    }

    @Override
    public ResultDto numByCode(DoctorNumListQuery query) {
        JSONObject jsonObject = HttpTool.postJson("opt_0005", JSONObject.toJSONString(query));
        Object result = jsonObject.get("result");
        if (result != null && !"[]".equals(result)) {
            return ResultDto.data(result);
        }
        return ResultDto.data(Collections.emptyList());
    }

    @Override
    public ResultDto lockNo(DoctorLockNoQuery query) {
        JSONObject jsonObject = HttpTool.postJson("opt_0017", JSONObject.toJSONString(query));
        Object result = jsonObject.get("result");
        if (result != null && !"[]".equals(result)) {
            return ResultDto.data(result);
        }
        return ResultDto.data(Collections.emptyList());
    }

    @Override
    public ResultDto reserveRegister(ReserveRegisterQuery query) {
        JSONObject jsonObject = HttpTool.postJson("opt_0018", JSONObject.toJSONString(query));
        Object result = jsonObject.get("result");
        if (result != null && !"[]".equals(result)) {
            return ResultDto.data(result);
        }
        return ResultDto.data(Collections.emptyList());
    }

    @Override
    public ResultDto patientHadReserve(PatientHadReserveQuery query) {
        JSONObject jsonObject = HttpTool.postJson("opt_0007", JSONObject.toJSONString(query));
        Object result = jsonObject.get("result");
        if (result != null && !"[]".equals(result)) {
            List<ReserveByPatientDto> list = JSONArray.parseArray(result + "", ReserveByPatientDto.class);
            if (list.size() == 0) {
                return ResultDto.data(Collections.emptyList());
            } else {
                PayOrderEntity entity = new PayOrderEntity();
                entity.setPatId(list.get(0).getPatId());
                entity.setRegId(list.get(0).getRegId());
                entity.setPayStatus(1);
                return ResultDto.data(payOrderMapper.select(entity));
            }

        }
        return ResultDto.data(Collections.emptyList());
    }

    @Override
    public ResultDto reserveCancel(ReserveCancelQuery query) {
        JSONObject jsonObject = HttpTool.postJson("opt_0019", JSONObject.toJSONString(query));
        Object result = jsonObject.get("result");
        if (result != null && !"[]".equals(result)) {
//            同时，需要对订单进行更新
            PayOrderEntity payOrderEntity = new PayOrderEntity();
            payOrderEntity.setPatId(query.getPatId());
            payOrderEntity.setRegId(query.getPatId());
            List<PayOrderDto> list = payOrderMapper.select(payOrderEntity);
            if (list.size() > 0) {
                payOrderEntity.setId(list.get(0).getId());
            }
            payOrderEntity.setPayStatus(4);
            payOrderEntity.setPayStatusName("取消");
            payOrderEntity.setUpdateTime(DateTool.format());
            payOrderMapper.updateById(payOrderEntity);
            return ResultDto.data(result);
        }
        return ResultDto.data(Collections.emptyList());
    }


    @Override
    public ResultDto add(DoctorVo vo) {
        vo.setDiagnosisMoney(vo.getDiagnosisMoney() * 100);
        vo.setRegisterMoney(vo.getRegisterMoney() * 100);
        vo.setMoneyFirst(vo.getMoneyFirst() * 100);
        vo.setMoneyImg(vo.getMoneyImg() * 100);
        vo.setMoneyMedic(vo.getMoneyMedic() * 100);
        vo.setMoneyVideo(vo.getMoneyVideo() * 100);
        vo.setMoneyVoice(vo.getMoneyVoice() * 100);
        vo.setCreateTime(DateTool.format());
        return ResultDto.data(doctorMapper.insert(JSONCopy.copy(vo, DoctorEntity.class)));
    }

    @Override
    public ResultDto update(DoctorVo vo) {
        vo.setDiagnosisMoney(vo.getDiagnosisMoney() * 100);
        vo.setRegisterMoney(vo.getRegisterMoney() * 100);
        vo.setMoneyFirst(vo.getMoneyFirst() * 100);
        vo.setMoneyImg(vo.getMoneyImg() * 100);
        vo.setMoneyMedic(vo.getMoneyMedic() * 100);
        vo.setMoneyVideo(vo.getMoneyVideo() * 100);
        vo.setMoneyVoice(vo.getMoneyVoice() * 100);
        vo.setUpdateTime(DateTool.format());
        return ResultDto.data(doctorMapper.updateById(JSONCopy.copy(vo, DoctorEntity.class)));
    }

    @Override
    public ResultDto delete(int id) {
        return ResultDto.data(doctorMapper.deleteById(id));
    }


    @Override
    public ResultDto status(int id) {
        return ResultDto.data(doctorMapper.status(id));
    }

    @Override
    public ResultDto selectScheduling(DoctorSchedulingVo vo) {
        JSONObject jsonObject = HttpTool.postJson("opt_0003", JSONObject.toJSONString(vo));
        if (jsonObject.get("result") == null) {
            return ResultDto.data(jsonObject);
        }
        List<DoctorSchedulingDto> list = JSONArray.parseArray(jsonObject.get("result").toString(), DoctorSchedulingDto.class);
// 需要将远程查询出的数据和本地的医生进行比较，如果本地没有，则新增医生到本地即可
//        注意，远程数据是排班信息，可以是很多条属于同一个医生，则需要筛选
        Map<String, DoctorSchedulingDto> map = new TreeMap<>();
        list.forEach(item -> map.put(item.getDoctorCode(), item));
        map.forEach((k, v) -> {
            DoctorEntity queryByCodeEntity = new DoctorEntity();
            queryByCodeEntity.setCode(k);
            List<DoctorDto> dto = doctorMapper.select(queryByCodeEntity);
            //            如果dto为空，则保存
            DoctorEntity doctorEntity = new DoctorEntity();
            doctorEntity.setName(v.getDoctorName());
            doctorEntity.setCode(v.getDoctorCode());
            doctorEntity.setDeptCode(v.getDeptCode());
            doctorEntity.setDeptName(v.getDeptName());
            doctorEntity.setSex(v.getDoctorSex());
            doctorEntity.setCampusCode(vo.getCampusCode());
            doctorEntity.setStatus(1);
            if (!StringTool.isBlank(v.getDoctorTitle())) {
                doctorEntity.setJobTitle(v.getDoctorTitle());
            }
            if (!StringTool.isBlank(v.getDoctorSpecialty())) {
                doctorEntity.setSpecialty(v.getDoctorSpecialty());
            }
            if (!StringTool.isBlank(v.getDoctorInfo())) {
                doctorEntity.setIntroduction(v.getDoctorInfo());
            }
            if (!StringTool.isBlank(v.getSitType())) {
                doctorEntity.setScheduleStatus(Integer.parseInt(v.getSitType()));
            }
            doctorEntity.setCampusName(v.getCampus());
            if (!StringTool.isBlank(v.getExpertType())) {
                doctorEntity.setExpertType(v.getExpertType());
            }
            if (!StringTool.isBlank(v.getRegFee())) {
                doctorEntity.setRegisterMoney(NumberTool.strToMoney(v.getRegFee()));
            }
            if (!StringTool.isBlank(v.getMedicalFee())) {
                doctorEntity.setDiagnosisMoney(NumberTool.strToMoney(v.getMedicalFee()));
            }

            if (dto.size() == 0) {
                doctorMapper.insert(doctorEntity);
            } else {
                doctorEntity.setId(dto.get(0).getId());
                doctorMapper.updateById(doctorEntity);
            }
        });
        DoctorEntity query = new DoctorEntity();
        List<DoctorDto> dtoList = doctorMapper.select(query);
        Map<String, DoctorDto> adminDoctorDtoMap = new TreeMap<>();
        dtoList.forEach(item -> adminDoctorDtoMap.put(item.getCode(), item));
//        将查询的数据添加到返回到前端的数据
        list.forEach(item -> {
            DoctorDto doctorDto = adminDoctorDtoMap.get(item.getDoctorCode());
            item.setDoctorInfo(doctorDto.getIntroduction());
            item.setDoctorSpecialty(doctorDto.getSpecialty());
            item.setHeadImg(doctorDto.getHeadImg());
            item.setServiceNum(doctorDto.getServiceNum());
            item.setEvaluateNum(doctorDto.getEvaluateNum());
            item.setLikesNum(doctorDto.getLikesNum());
            item.setForwardsNum(doctorDto.getForwardsNum());
        });

        return ResultDto.data(list);
    }

    @Override
    public ResultDto selectDepartmentNumList(DoctorAreaTimeVo vo) {
        JSONObject jsonObject = HttpTool.postJson("opt_0006", JSONObject.toJSONString(vo));
        if (jsonObject.get("result") == null) {
            return ResultDto.data(Collections.emptyList());
        }
        List<DoctorAreaTimeDto> list = JSONArray.parseArray(jsonObject.get("result").toString(), DoctorAreaTimeDto.class);
        if (list.size() == 0) {
            return ResultDto.data(Collections.emptyList());
        }
        if (vo.getDoctorCode() == null) {
            return ResultDto.data(jsonObject.get("result"));
        }
        DoctorEntity entity = new DoctorEntity();
        entity.setCode(vo.getDoctorCode());
        List<DoctorDto> doctorDtoList = doctorMapper.select(entity);
        if (doctorDtoList.size() > 0) {
            DoctorEntity updateEntity = JSONCopy.copy(doctorDtoList.get(0), DoctorEntity.class);
            updateEntity.setAddress(list.get(0).getSitAddress());
            doctorMapper.updateById(updateEntity);
        }
        return ResultDto.data(jsonObject.get("result"));
    }

    @Override
    public ResultDto selectByDeptOrDoctor(DoctorVo vo) {
        DoctorEntity entity = JSONCopy.copy(vo, DoctorEntity.class);
        return ResultDto.data(doctorMapper.selectByDeptOrDoctorCount(entity), doctorMapper.selectByDeptOrDoctor(entity));
    }

    @Override
    public ResultDto serviceNum(DoctorVo vo) {
        DoctorEntity entity = JSONCopy.copy(vo, DoctorEntity.class);
        entity.setStatus(1);
        entity.setCreateTime(DateTool.format());
        return ResultDto.data(doctorMapper.serviceNum(entity));
    }

    @Override
    public ResultDto evaluateNum(DoctorVo vo) {
        DoctorEntity entity = JSONCopy.copy(vo, DoctorEntity.class);
        entity.setStatus(1);
        entity.setCreateTime(DateTool.format());
        return ResultDto.data(doctorMapper.evaluateNum(entity));
    }

    @Override
    public ResultDto likesNum(DoctorVo vo) {
        DoctorEntity entity = JSONCopy.copy(vo, DoctorEntity.class);
        entity.setStatus(1);
        entity.setCreateTime(DateTool.format());
        return ResultDto.data(doctorMapper.likesNum(entity));
    }

    @Override
    public ResultDto forwardsNum(DoctorVo vo) {
        DoctorEntity entity = JSONCopy.copy(vo, DoctorEntity.class);
        entity.setStatus(1);
        entity.setCreateTime(DateTool.format());
        return ResultDto.data(doctorMapper.forwardsNum(entity));
    }
}
